package org.paradise.dms.web.action.lodgemgr;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.log4j.Logger;
import org.directwebremoting.annotations.RemoteProxy;
import org.paradise.dms.pojo.Dormitory;
import org.paradise.dms.pojo.Student;
import org.paradise.dms.services.DormitoryService;
import org.paradise.dms.services.StudentLodgeMgrService;
import org.paradise.dms.web.action.DMSBaseAction;
import org.paradise.dms.web.tools.DWRPage;
import org.paradise.dms.web.tools.Pager;
import org.paradise.dms.web.tools.PagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dheaven.framework.dao.DaoException;

/**
 * 
 * Description: 学生住宿管理action（包括：调换宿舍，退宿办理,住宿时限等）
 * 
 * 
 * Copyright (c) 2008-2009 paraDise sTudio(DT). All Rights Reserved.
 * 
 * @version 1.0 2009-3-23 下午08:04:16 李双江（paradise.lsj@gmail.com）created
 */
@Service
@RemoteProxy(name = "studentLodgeMgrAction")
public class StudentLodgeMgrAction extends DMSBaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7057558235142106271L;
	private static Logger log = Logger.getLogger(StudentLodgeMgrAction.class);
	@Autowired
	private StudentLodgeMgrService studentLodgeMgrService;
	@Autowired
	private DormitoryService dormitoryService;
	@Autowired
	private PagerService pagerService;
	private Pager pager;
	private String batchDeleteSql;
	protected String currentPage;
	protected String totalRows;
	protected String pagerMethod;

	public String getTotalRows() {
		return totalRows;
	}

	public void setTotalRows(String totalRows) {
		this.totalRows = totalRows;
	}

	public String getPagerMethod() {
		return pagerMethod;
	}

	public void setPagerMethod(String pagerMethod) {
		this.pagerMethod = pagerMethod;
	}

	public DormitoryService getDormitoryService() {
		return dormitoryService;
	}

	public void setDormitoryService(DormitoryService dormitoryService) {
		this.dormitoryService = dormitoryService;
	}

	public PagerService getPagerService() {
		return pagerService;
	}

	public void setPagerService(PagerService pagerService) {
		this.pagerService = pagerService;
	}

	public Pager getPager() {
		return pager;
	}

	public void setPager(Pager pager) {
		this.pager = pager;
	}

	public String getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(String currentPage) {
		this.currentPage = currentPage;
	}

	public StudentLodgeMgrService getStudentLodgeMgrService() {
		return studentLodgeMgrService;
	}

	public void setStudentLodgeMgrService(StudentLodgeMgrService studentLodgeMgrService) {
		this.studentLodgeMgrService = studentLodgeMgrService;
	}

	public String getBatchDeleteSql() {
		return batchDeleteSql;
	}

	public void setBatchDeleteSql(String batchDeleteSql) {
		this.batchDeleteSql = batchDeleteSql;
	}

	/**
	 * 
	 * Description: 根据学号获得一个学生的stuList(调换宿舍时查学生，在单人分配的时候也要查学生，这个方法可以重用)
	 * 
	 * @Version1.0 2009-3-24 上午10:44:39 李双江（paradise.lsj@gmail.com）创建
	 * @return
	 * @throws DaoException
	 */
	@SuppressWarnings("unchecked")
	public String[] searchStudentByStudentNo(String studentno) throws DaoException {
		// 7476,40553015,李双江,男,0,信息工程学院
		// ,测控技术与仪器,测控0501,<null>,0,/uploadedFiles/studentPicture/40553015.jpg,汉族,0,1988-11-23
		// 00:00:00.0,本科
		// 调用StudentLodgeMgrService里面的方法，实现返回stuList
		List stuList = new ArrayList();
		stuList = studentLodgeMgrService.searchStudentByStudentNo(studentno);
		if (stuList != null && stuList.size() > 0) {
			Object[] obj = (Object[]) stuList.get(0);
			// 最后一项是"本科"
			String[] str = { obj[0] + "", obj[1] + "", obj[2] + "", obj[3] + "", obj[4] + "", obj[5] + "", obj[6] + "", obj[7] + "", obj[14] + "", };
			return str;
		} else {
			String[] str = { "Student Not Found!!" };
			log.warn("DMS_warn：查询学号为" + studentno + "的学生结果为空!");
			return str;
		}

	}

	/**
	 * 
	 * Description: 根据公寓ID，宿舍号查询宿舍。其中宿舍号可选 若宿舍号不为空，则查出该宿舍； 若宿舍号为空，则查出该公寓中所有可用宿舍
	 * 参数 studentdormitorytpye对应于dormitory表中的dormitoryconcretefuncid,即住宿人员的类型,如学生,导员,临时住宿人员
	 * @Version1.0 2009-3-24 下午10:34:39 闫克 （kurtyan777@gmail.com） created
	 * @Version 1.1 2009-3-26 李双江删除接收到参数
	 * @return
	 * @throws DaoException
	 * @throws DaoException
	 */
	public String[] getDormByApartIdAndDormName(String apartmentid, String dormitoryname,int studentdormitorytpye) throws DaoException {
		List<Dormitory> dormList = new ArrayList<Dormitory>();
		if ((dormitoryname != null) && dormitoryname.length() > 0) { // 宿舍名存在
			dormList = (List<Dormitory>) studentLodgeMgrService.getDormByApartIdAndDormName(apartmentid, dormitoryname,studentdormitorytpye);
			if (dormList != null && dormList.size() > 0) {
				log.info(ReflectionToStringBuilder.toString(dormList.get(0)).toString());
				// dormitoryid=11,allocationid=2,apartmentid=1,dormitorystatusid=-1,dormitoryname=111
				// ,dormitorydisplayname=1号楼 1层111
				// 房间,dormitorysex=0,dormitorytelephone=0,dormitoryroomtype=6,dormitoryfee=900,dormitorysort=101011,
				// dormitoryinstudentnum=0,dormitoryfloorno=1,dormitoryind=1,dormitoryfunction=-1
				int inAmount = studentLodgeMgrService.getAvailInDormAmountByDormId(dormList.get(0).getDormitoryid()+"");
				if (inAmount < 0) {
					return null;
				}
				int availAmount = Integer.parseInt(dormList.get(0).getDormitorylodgetype() + "") - inAmount;
				if (availAmount < 0) {
					return null;
				}
				String[] mystr = { dormList.get(0).getDormitoryid() + "", dormList.get(0).getDormitorydisplayname(), dormList.get(0).getDormitorylodgetype(), dormList.get(0).getDormitorysex()+"", availAmount + "" };
				log.info(ReflectionToStringBuilder.toString(mystr).toString());
				return mystr;

			}
		}
		return null;
	}

	/**
	 * 
	 * Description: 返回可以使用宿舍的总条数
	 * 参数 studentdormitorytpye对应于dormitory表中的dormitoryconcretefuncid,即住宿人员的类型,如学生,导员,临时住宿人员
	 * @Version1.0 May 19, 2009 1:03:49 PM 李双江（paradise.lsj@gmail.com）创建
	 * @param apartmentid
	 * @param floorno
	 * @return
	 */
	public int getTotalAvailDormRowsAction(String apartmentid, String floorno,int studentdormtorytype) {
		return dormitoryService.getTotalAvailDormRows(apartmentid, floorno,studentdormtorytype);
	}

	/**
	 * 
	 * Description: 分页查询可以使用的宿舍
	 * 参数 studentdormitorytpye对应于dormitory表中的dormitoryconcretefuncid,即住宿人员的类型,如学生,导员,临时住宿人员
	 * @Version1.0 May 19, 2009 1:03:56 PM 李双江（paradise.lsj@gmail.com）创建
	 * @param pageNum
	 * @param apartmentid
	 * @param floorno
	 * @param session
	 * @return
	 */
	@SuppressWarnings( { "unchecked", "static-access" })
	public JSONArray getAvailDromPerPageByApartmentID(int pageNum, String apartmentid, String floorno,int studentdormitorytype, String totalRow, HttpSession session) {
		List dlist = new ArrayList();
		DWRPage page = new DWRPage();
		page.setPageProperties(Integer.parseInt(totalRow), 5);
		page.setCurrentPage(pageNum);
		session.setAttribute("page", page);
		int cp = (page.getCurrentPage() - 1) * 5;
		int ps = page.getPageSize();
		List availDormsList = dormitoryService.listAvailDormitoryByApartmentid(apartmentid, floorno,studentdormitorytype, ps, cp);
		if (availDormsList != null && availDormsList.size() > 0) {
			for (int k = 0; k < availDormsList.size(); k++) {
				List d = new ArrayList();
				Object[] o = (Object[]) availDormsList.get(k);
				int dormitoryid = (Integer) o[0]; // dormid
				int inAmount = (Integer) o[1]; // 已经入住人数
				String dormname = (String) o[2]; // 宿舍显示名称
				int dormitoryroomtype = (Integer) o[3]; // 房型
				int dormitorysex = (Integer) o[4]; // 性别
				int avialno = dormitoryroomtype - inAmount;
				//log.info("dormitoryid:\t" + dormitoryid + "\t" + "inAmount\t" + inAmount);
				//log.info("dormname:\t" + dormname + "\t" + "dormitoryroomtype\t" + dormitoryroomtype + "dormitorysex\t" + dormitorysex);
				d.add(dormitoryid);
				d.add(dormname);
				d.add(dormitorysex);
				d.add(avialno);
				d.add(dormitoryroomtype);
				dlist.add(d);
			}
			JSONArray jo = new JSONArray().fromObject(dlist);
			return jo;
		}
		return null;
	}

	/**
	 * 
	 * Description: 返回preid总房间
	 * 
	 * @Version1.0 Apr 22, 2009 9:04:15 PM 李双江（paradise.lsj@gmail.com）创建
	 * @param dormpreid
	 * @return
	 */
	public int getTotalAvailPreIdDormRows(String dormpreid) {
		return dormitoryService.getTotalAvailPreIdDormRows(dormpreid);
	}

	/**
	 * 
	 * Description: 通过preid获取宿舍的信息（及时分配时用到的）
	 * 
	 * @Version1.0 Apr 22, 2009 3:14:26 PM 李双江（paradise.lsj@gmail.com）创建
	 * @param pageNum
	 * @param dormpreid
	 * @param session
	 * @return
	 */
	// ================================
	@SuppressWarnings( { "unchecked", "static-access" })
	public JSONArray getAvailDormPerPageByPreID(int pageNum, int totalRow, String dormpreid, HttpSession session) {
		List dlist = new ArrayList();
		DWRPage page = new DWRPage();
		page.setPageProperties(totalRow, 5);
		page.setCurrentPage(pageNum);
		session.setAttribute("page", page);
		int cp = (page.getCurrentPage() - 1) * 5;
		int ps = page.getPageSize();
		List availDormsList = dormitoryService.listAvailDromPerPageByPreID(dormpreid, ps, cp);
		if (availDormsList != null && availDormsList.size() > 0) {
			for (int k = 0; k < availDormsList.size(); k++) {
				List d = new ArrayList();
				Object[] o = (Object[]) availDormsList.get(k);
				int dormitoryid = (Integer) o[0];
				int inAmount = (Integer) o[1];
				String dormname = (String) o[2];
				int dormitoryroomtype = (Integer) o[3];
				int dormitorysex = (Integer) o[4];
				int availno = dormitoryroomtype - inAmount;
				// log.info("dormitoryid:\t" + dormitoryid + "\t" + "inAmount\t"
				// + inAmount);
				// log.info("dormname:\t" + dormname + "\t" +
				// "dormitoryroomtype\t" + dormitoryroomtype + "dormitorysex\t"
				// + dormitorysex);
				d.add(dormitoryid);
				d.add(dormname);
				d.add(dormitoryroomtype);
				d.add(availno);
				d.add(dormitorysex);
				dlist.add(d);
			}
			JSONArray jo = new JSONArray().fromObject(dlist);
			return jo;
		}
		return null;
	}

	@SuppressWarnings("static-access")
	public JSONObject getPage(HttpSession session) {
		JSONObject joa = new JSONObject().fromObject((DWRPage) session.getAttribute("page"));
		return joa;
	}

	/**
	 * 
	 * Description: 根据studentid 和dormitoryid进行人和空宿舍分配
	 * 
	 * 
	 * @Version1.0 2009-3-26 下午10:46:36 李双江（paradise.lsj@gmail.com）创建
	 * @param studentid
	 * @param apartmentid
	 * @return
	 * @throws DaoException
	 * @throws NumberFormatException
	 */
	public String allocateSingleStudent(String studentid, String dormitoryid) throws NumberFormatException, DaoException {
		// allocateInfo =
		// studentLodgeMgrService.transferSingleStudentToEmptyBed(Integer.parseInt(studentid),
		// Integer.parseInt(dormitoryid));
		return studentLodgeMgrService.allocateSingleStudent(Integer.parseInt(studentid), Integer.parseInt(dormitoryid));

	}

	/**
	 * 
	 * Description:调至空床
	 * 
	 * @Version1.0 Apr 9, 2009 10:36:58 PM 李双江（paradise.lsj@gmail.com）创建
	 * @param studentid
	 * @param dormitoryid
	 * @return
	 * @throws DaoException
	 * @throws NumberFormatException
	 */
	public String transferStudenttoEmptyBed(String studentid, String dormitoryid) throws NumberFormatException, DaoException {
		return studentLodgeMgrService.transferSingleStudentToEmptyBed(Integer.parseInt(studentid), Integer.parseInt(dormitoryid));
	}

	/**
	 * 
	 * Description: 根据学号，给2个学生调换宿舍
	 * 
	 * @Version1.0 2009-3-27 上午04:56:43 李双江（paradise.lsj@gmail.com）创建
	 * @param stu_a_no
	 * @param stu_b_no
	 * @return
	 * @throws DaoException
	 * @throws NumberFormatException
	 */
	public String swapStudents(String stu_a_no, String stu_b_no) throws NumberFormatException, DaoException {
		return studentLodgeMgrService.swapStudents(Integer.parseInt(stu_a_no), Integer.parseInt(stu_b_no));
	}

	/**
	 * 
	 * Description:根据学生学号查询该学生住宿信息
	 * 
	 * @Version1.0 2009-4-4 上午01:25:12 李双江（paradise.lsj@gmail.com）创建
	 * @param studentno
	 * @return
	 * @throws DaoException
	 */
	@SuppressWarnings("unchecked")
	public JSONArray searchStudentLodgeInfoByNo(String studentno) throws DaoException {
		JSONArray json = new JSONArray();
		try {
			List lst = studentLodgeMgrService.queryStudentLodgeInfo(studentno);
			if (lst != null && lst.size() > 0) {
				Student s = (Student) lst.get(0);
				if (lst.size() == 3) { // 含有住宿信息
					Dormitory d = (Dormitory) lst.get(1);
					json.add(s.getStudentid());
					json.add(s.getStudentname());
					json.add(d.getDormitorydisplayname());
					log.info(json + "含有住宿信息");
					return json;
				} else { // 有学生信息和errorMsg
					json.add(s.getStudentid());
					json.add(s.getStudentname());
					json.add(lst.get(1));
					log.info(json + "有学生信息和errorMsg");
					// [16,"李志梅","该学生尚未分配宿舍"]--格式
					return json;
				}
			}
		} catch (Exception e) {
			log.info("DMS_error:学生学号查询该学生住宿信息有误！");
			log.info("DMS_error:错误原因！" + e);
		}
		return null;
	}

	/**
	 * 
	 * Description: 根据一个studentid去办理单个学生的退宿
	 * 
	 * @Version1.0 2009-4-4 上午02:21:51 李双江（paradise.lsj@gmail.com）创建
	 * @param studentid
	 * @throws NumberFormatException
	 */
	public String checkOutAsingleStudentByStudentID(String studentid) throws NumberFormatException {
		try {
			return studentLodgeMgrService.studentCheckOut(Integer.parseInt(studentid));
		} catch (DaoException e) {
			log.info("DMS_error:根据一个studentid去办理单个学生的退宿有误！");
			log.info("DMS_error:错误原因！" + e);
		}
		return "查询学生结果有误";
	}

	/**
	 * Description: 批量退宿 kurtyan777@gmail.com
	 * 
	 * 
	 * @return
	 */
	public String checkOutBatchStudent(String sql) {
		return studentLodgeMgrService.studentBatchCheckout(sql);
	}

	/**
	 * 
	 * Description: 批量分配宿舍
	 * 
	 * @Version1.0 2009-4-6 下午04:33:46 李双江（paradise.lsj@gmail.com）创建
	 * @param stuList
	 * @param dormitoryList
	 * @param startintime(精确到年月日)
	 * @param endouttime(精确到年月日)
	 * @return
	 */
	public String allocateBatchStudent(String[][] stuList, String[][] dormitoryList, String startintime, String endouttime,String order) {
		// for (int i = 0; i < stuList.length; i++) {
		// log.info(stuList[i][0]);
		// log.info(stuList[i][1]);
		// }
		// for (int j = 0; j < dormitoryList.length; j++) {
		// log.info(dormitoryList[j][0]);
		// log.info(dormitoryList[j][1]);
		// }
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date sdate = null;
		Date edate = null;
		try {
			sdate = df.parse(startintime);
			edate = df.parse(endouttime);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		return studentLodgeMgrService.allocateBatchStudent(stuList, dormitoryList, sdate, edate,order);
	}

	/**
	 * 
	 * Description: 根据学号查看住宿时限信息
	 * 
	 * @Version1.0 Apr 15, 2009 1:27:01 PM 李双江（paradise.lsj@gmail.com）创建
	 * @param studentno
	 * @return
	 * @throws ParseException
	 */
	@SuppressWarnings( { "unchecked", "static-access" })
	public JSONArray getlodgeTimeMgrInfoByStudentNo(String studentno) throws ParseException {
		List timeInfoList = new ArrayList();
		// return including
		// studentid, studentname, studentno, studentbedstartintime,
		// studentbedendouttime, dormitorydisplayname, dormitoryid
		List list = studentLodgeMgrService.getLodgeTimeByStudentNo(studentno.trim());
		if (list != null & list.size() > 0) {
			Object[] obj = (Object[]) list.get(0);
			Object st = obj[3].toString().substring(0, 10); // 时间截取
			Object et = obj[4].toString().substring(0, 10);
			timeInfoList.add(obj[0]);
			timeInfoList.add(obj[1]);
			timeInfoList.add(obj[2]);
			timeInfoList.add(st);
			timeInfoList.add(et);
			timeInfoList.add(obj[5]);
			timeInfoList.add(obj[6]);
			JSONArray timInfoArray = new JSONArray().fromObject(timeInfoList);
			return timInfoArray;
		}
		return null;
	}

	/**
	 * 
	 * Description:更改用户住宿时限
	 * 
	 * @Version1.0 Apr 18, 2009 11:16:18 PM 李双江（paradise.lsj@gmail.com）创建
	 * @param studentid
	 * @param startintime
	 * @param endouttime
	 * @return
	 */
	public String updateLodgeTimeMgrInfo(String studentid, String startintime, String endouttime) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date sdate = null;
		Date edate = null;
		try {
			sdate = df.parse(startintime);
			edate = df.parse(endouttime);
		} catch (ParseException e1) {
			log.info("DMS_error:更改用户住宿时限！");
			log.info("DMS_error:错误原因！" + e1);
		}
		return studentLodgeMgrService.updateStudentLodgeTime(studentid.trim(), sdate, edate);
	}
	public String[] getPreassignDateByPreID(int id){
		List list =  studentLodgeMgrService.getPreassignDateByPreID(id);
		if (list != null & list.size() > 0) {
			Object[] obj = (Object[]) list.get(0);
			String [] s = new String[2];
			if(null != obj[0]){
				s[0] = obj[0].toString().substring(0, 10);// 时间截取
			}
			if(null != obj[1]){
				s[1] = obj[1].toString().substring(0, 10);
			}
			return s;
		}else{
			return null;
		}
	}
}
